<?php
class Product_Basic extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
				# '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'product_basic',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}

/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	
	static function createSingle()
	{
		
	}
	
	/**
	 * 批量新建基础产品
	 * @param $start_number 起始编号
	 * @param $end_number 结束编号
	 * @param $number_length 编号长度
	 * @param $categories_id 分类id
	 * @param $weight 基础产品净重
	 */
	static function createMulti($start_number, $end_number, $number_length, $categories_id, $weight)
	{
		$number_prefix = (Helper_Plu_Number::$status)?Helper_Plu_Number::getNumberPrefixByCategoryId($categories_id):'';
		if (intval($start_number) <= intval($end_number))
		{
			$product_basic = array();
			$ack = SUCCESS;
			$message = array();
			for ($i = $start_number; $i <= $end_number; $i++)
			{
				$number = $number_prefix.(str_pad($i, $number_length, '0', STR_PAD_LEFT));
				$product_in_db = Product_Basic::find('number=?', $number)->asArray()->getOne();
				if ($product_in_db)
				{
					$ack = PARTIAL_FAILURE;
					$message[] = $i . EXISTS;
					$product_basic[] = array('product_basic_id' => '', 'number' => $i);
				}
				else
				{
					$product = new Product_Basic();
					$product->number = $number;
					$product->product_categories_id = $categories_id;
					$product->weight = $weight;
					$product->create_time = CURRENT_DATETIME;
					$product->save();
					$product_id = mysql_insert_id();
					$product_basic[] = array('product_basic_id' => $product_id, 'number' => $number);
				}
			}
			return array(
				'ack' => $ack,
				'message' => $message ? implode(',', $message) : '',
				'product_basic' => $product_basic
			);
		}
		else
		{
			return array(
				'ack' => FAILURE,
				'message' => 'start number greater than end number'
			);
		}
	}
	
	/**
	 * 按条件搜索产品基本资料
	 * @param $condition 搜索条件
	 * @param $cp 当前页
	 * @param $ps 页大小
	 * @return 产品基本信息
	 */
	static function search($condition, $cp, $ps, $sort_order = '')
	{
		$columns = array(
			'product_basic.*',
			'product_provider.name as preferred_provider_name',
			'user.name as follow_user_name'
		);
		$where = Product_Basic::buildSearchWhere($condition);
		if ($cp == 0 && $ps == 0)
		{
			$select = Product_Basic::find($where)
				->joinLeft('product_provider', '', 'product_provider.id=product_basic.preferred_provider_id')
				->joinLeft('user', '', 'user.id=product_provider.follow_user_id')
				->order($sort_order)->setColumns($columns);
			$pagination = array();
		}
		else
		{
			$select = Product_Basic::find($where)
				->joinLeft('product_provider', '', 'product_provider.id=product_basic.preferred_provider_id')
				->joinLeft('user', '', 'user.id=product_provider.follow_user_id')
				->order($sort_order)->setColumns($columns)->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$product_basic = $select->asArray()->getAll();
		return array(
			'ack' => SUCCESS,
			'message' => '',
			'data' => $product_basic,
			'pagination' => $pagination
		);
	}
	
	/**
	 * 编辑产品基本信息
	 * @param $product_basic
	 */
	static function edit($product_basic)
	{
		$judge = Product_Basic::judgeEdit($product_basic);
		if ($judge['ack'] == SUCCESS)
		{
			$check_in_db = Product_Basic::find('number=?', $product_basic['number'])->getOne();
			$check_in_db->name = trim($product_basic['name']);
			$check_in_db->weight = trim($product_basic['weight']);
			$check_in_db->purchase_price = isset($product_basic['purchase_price']) ? $product_basic['purchase_price'] : $check_in_db['purchase_price'];
			$check_in_db->preferred_provider_id = $product_basic['preferred_provider_id'];
			$check_in_db->product_categories_id = $product_basic['product_categories_id'];
			$check_in_db->declared_value = $product_basic['declared_value'];
			$check_in_db->declared_name_cn = trim($product_basic['declared_name_cn']);
			$check_in_db->declared_name_en = trim($product_basic['declared_name_en']);
			$check_in_db->notes = trim($product_basic['notes']);
			$check_in_db->img = trim($product_basic['img']);
			$check_in_db->save();
		}
		return array('ack' => $judge['ack'], 'message' => $judge['message']);
	}
	
	static function judgeEdit($product_basic)
	{
		$check_in_db = Product_Basic::find('number=?', str_pad($product_basic['number'], 6, '0', STR_PAD_LEFT))->asArray()->getOne();
		$error_message = '';
		if ($check_in_db)
		{
			if (empty($product_basic['name']))
			{
				$error_message .= '产品名称不能为空！';
			}
			if (empty($product_basic['preferred_provider_id']))
			{
				$error_message .= '供应商ID不能为空！';
			}
			else
			{
				$check_in_provider = Product_Provider::find('id=?', $product_basic['preferred_provider_id'])->asArray()->getOne();
				if (!$check_in_provider)
				{
					$error_message .= '供应商ID不存在系统！';
				}
			}
			if (empty($product_basic['product_categories_id']))
			{
				$error_message .= '分类ID不能为空！';
			}
			else
			{
				$check_in_product_categories = Product_Categories::find('id=?', $product_basic['product_categories_id'])->asArray()->getOne();
				if (!$check_in_product_categories)
				{
					$error_message .= '分类ID不存在系统！';
				}
			}
			if (empty($product_basic['declared_value']))
			{
				$error_message .= '申报价值不能为空!';
			}
			if (empty($product_basic['declared_name_cn']))
			{
				$error_message .= '申报中文名不能为空！';
			}
			if (empty($product_basic['declared_name_en']))
			{
				$error_message .= '申报英文名不能为空！';
			}
		}
		else
		{
			$error_message .= '产品编号不存在系统！';
		}
		if ($error_message)
		{
			return array('ack' => FAILURE, 'message' => $error_message);
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	/**
	 * 导入产品资料，限制重复导入采购价不能更改
	 * @param 产品资料  $product_basic
	 */
	static function import($product_basic)
	{
		$judge = Product_Basic::judgeEdit($product_basic);
		if ($judge['ack'] == SUCCESS)
		{
			$check_in_db = Product_Basic::find('number=?', $product_basic['number'])->getOne();
			if ($check_in_db['purchase_price'] == $product_basic['purchase_price'] || $check_in_db['purchase_price'] == NULL)
			{
				$check_in_db->name = trim($product_basic['name']);
				$check_in_db->weight = trim($product_basic['weight']);
				$check_in_db->purchase_price = $product_basic['purchase_price'];
				$check_in_db->preferred_provider_id = $product_basic['preferred_provider_id'];
				$check_in_db->product_categories_id = $product_basic['product_categories_id'];
				$check_in_db->declared_value = $product_basic['declared_value'];
				$check_in_db->declared_name_cn = trim($product_basic['declared_name_cn']);
				$check_in_db->declared_name_en = trim($product_basic['declared_name_en']);
				$check_in_db->notes = trim($product_basic['notes']);
				$check_in_db->img = trim($product_basic['img']);
				$check_in_db->save();
			}
			else
			{
				return array('ack' => FAILURE, 'message' => '限制修改采购价，请通知相关人员统一修改！');
			}
		}
		return array('ack' => $judge['ack'], 'message' => $judge['message']);
	}
	
	static function editNote($product_basic_id, $note, $flag)
	{
		$judge_result = Product_Basic::judgeEditNote($product_basic_id, $flag);
		if ($judge_result['ack'] == SUCCESS)
		{
			$product = Product_Basic::find('id=?', $product_basic_id)->getOne();
			$product->purchase_note = ($product->purchase_note) ?  $product->purchase_note . "<br />" . CURRENT_USER_NAME . '[' . date('m-d', CURRENT_TIMESTAMP) . ']：' . $note : CURRENT_USER_NAME . '[' . date('m-d', CURRENT_TIMESTAMP) . ']：' . $note;
			$product->purchase_note_flag = $flag;
			$product->purchase_note_user_id = CURRENT_USER_ID;
			$product->purchase_note_time = CURRENT_DATETIME;
			$product->save();
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	static function judgeEditNote($product_basic_id, $flag)
	{
		$check_in_db = Product_Basic::find('id=?', $product_basic_id)->asArray()->getOne();
		if ($check_in_db)
		{
			if ($check_in_db['purchase_note_flag'] < $flag || $flag == Q::ini('custom_flag/product_basic_purchase_note_flag/repeat/value'))	
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'SKU=' . $check_in_db['number'] . '备注状态为：' . Helper_BSS_Normal::getIniOne('product_basic_purchase_note_flag', 'value', $check_in_db['purchase_note_flag'], 'name') . '，如需修改请勾选重复备注！');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'SKU=' . $check_in_db['number'] . '产品不存在!');
		}
	}
	
	static function updatePurchasePrice($product_basic_id, $purchase_price)
	{
		$product_basic = Product_Basic::find('id=?', $product_basic_id)->getOne();
		if ($product_basic['id'])
		{
			$product_basic->last_purchase_price = $purchase_price;
			if ($product_basic['highest_purchase_price'] < $purchase_price || ! $product_basic['highest_purchase_price'])
			{
				$product_basic->highest_purchase_price = $purchase_price;
			}
			if ($product_basic['lowest_purchase_price'] > $purchase_price || ! $product_basic['lowest_purchase_price'])
			{
				$product_basic->lowest_purchase_price = $purchase_price;
			}
			$product_basic->save();
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'product basic is not exists');
		}
	}
	
	/**
	 * 组装搜索条件
	 * @param $condition 条件数组
	 */
	static function buildSearchWhere($condition)
	{
		$where = '1';
		if (isset($condition['limit']) && $condition['limit'] || CURRENT_USER_NAME == 'langyi')
		{
			$where .= ' and user.id=' . CURRENT_USER_ID;
		}
		if ( ! empty($condition['start_number']))
		{
			$where .= ' and product_basic.number like "' . $condition['start_number']. '%"';
		}
		if ( ! empty($condition['end_number']))
		{
			$where .= ' and product_basic.number like "' . $condition['end_number'] . '"';
		}
		if ( ! empty($condition['name']))
		{
			$where .= ' and product_basic.name like \'%' . $condition['name'] . '%\'';
		}
		if ( ! empty($condition['preferred_provider_name']))
		{
			$where .= ' and product_provider.name like \'%' . $condition['preferred_provider_name'] . '%\'';
		}
		if ( ! empty($condition['product_categories_id']))
		{
			$product_categories_ids = Product_Categories::getOffspringById($condition['product_categories_id']);
			array_push($product_categories_ids, $condition['product_categories_id']);
			$where .= ' and product_basic.product_categories_id in (' . implode(',', $product_categories_ids) . ')';
		}
		if ( ! empty($condition['ids']))
		{
			$where .= ' and product_basic.id in (' . implode(',', $condition['ids']) . ')';
		}
		if ( ! empty($condition['number_or_name']))
		{
			$where .= ' and (product_basic.number like \'' . $condition['number_or_name'] . '%\' or product_basic.name like \'%' . $condition['number_or_name'] . '%\')';
		}
		if ( ! empty($condition['product_numbers']))
		{
			$product_numbers = Q::Normalize($condition['product_numbers'], ",");
			$where .= ' and product_basic.number in (\'' . implode('\',\'', $product_numbers) . '\')';
		}
		if ( ! empty($condition['follow_user_id']))
		{
			$where .= ' and product_provider.follow_user_id=' . $condition['follow_user_id'];
		}
		if (isset($condition['undone']))
		{
			$where .= ' and (product_basic.name is NULL or product_basic.name=\'\' or product_basic.preferred_provider_id is NULL or product_basic.preferred_provider_id=0 or product_basic.preferred_provider_id=\'\' or product_basic.declared_name_en is NULL or product_basic.declared_name_en=\'\' or product_basic.declared_value is NULL or product_basic.declared_value=\'\' or product_basic.declared_value=0 or product_basic.declared_name_cn is NULL or product_basic.declared_name_cn=\'\' or product_categories_id=0 or product_categories_id=\'\' or weight=0 or weight=\'\' or purchase_price is NULL or purchase_price=0 or purchase_price=\'\')';
		}
		if (isset($condition['no_follow_user']))
		{
			$where .= ' and (product_basic.preferred_provider_id is NULL or product_basic.preferred_provider_id=0)';
		}
		if (! empty($condition['is_diff_flag']))
		{
			$where .= ' and product_basic.purchase_price!=product_basic.last_purchase_price';
		}
		return $where;
	}
}